package cn.dicraft.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 消费端
 * @author 烛远
 * @date 2024/8/29 17:20
 */
@Slf4j
public class ChannelFutureEventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        // 带有Future,Promise 的类型都是和异步方法配套使用，用来处理结果
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override //在建立连接后被调用
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                // connect是异步非阻塞的方法，main发起调用，真正执行connect连接的是nio线程
                .connect(new InetSocketAddress("localhost", 8080)); //连接建立慢

        /*
        // 2.1 使用 sync方法同步处理结果
        channelFuture.sync(); //阻塞住当前线程，直到nio线程建立完毕
        // 无阻塞的向下执行获取channel
        Channel channel = channelFuture.channel();
        log.debug("{}", channel);
        channel.writeAndFlush("hello world");
        */

        // 2.2 使用 addListener(回调对象) 方法处理异步结果
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            // 在nio线程连接建立好之后，会调用 operationComplete
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                log.debug("{}", channel);
                channel.writeAndFlush("hello world");
            }
        });
    }
}
